package cn.cs.mathgo.app.server.authentication;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cs.mathgo.app.entity.UserEntity;
import cn.cs.mathgo.app.util.TokenUtils;
import cn.cs.mathgo.common.AjaxJson;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 认证成功后做的处理
 * ClassName: ImoocAuthenticationSuccessHandler 
 * @Description:  认证成功后做的处理
 */
@Component("authenticationSuccessHandler")
public class AuthenticationSuccessHandler
		//spring默认的登录成功处理器，实现了AuthenticationSuccessHandler接口，适配登录后 重定向和返回json两种用这个实现
		extends SavedRequestAwareAuthenticationSuccessHandler 
		//返回json用这个实现
		/*implements AuthenticationSuccessHandler*/{

	private Logger logger = LoggerFactory.getLogger(getClass());

	//springmvc启动会自动注册一个ObjectMapper
	@Autowired
	private ObjectMapper objectMapper;



	@Autowired
	private TokenUtils tokenUtils;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
//		super.onAuthenticationSuccess(request,response,authentication);
		logger.info("登录成功");
		//获取请求头里Authorization信息
		String header = request.getHeader("Authorization");

			OAuth2AccessToken accessToken = tokenUtils.getOAuth2AccessToken(header, authentication, request);
			//OAuth2AccessToken accessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
			response.setHeader("Authorization",accessToken.getTokenType()+" "+accessToken.getValue());
			response.setContentType("application/json;charset=UTF-8");
			UserEntity userEntity =(UserEntity) authentication.getPrincipal();

			addCrossHeader(response);

			response.getWriter().write( objectMapper.writeValueAsString(AjaxJson.success(accessToken)));
			response.getWriter().flush();
	}

	private void addCrossHeader(HttpServletResponse response) {
		response.addHeader("Access-Control-Allow-Origin",
				"*");
		response.setHeader("Access-Control-Allow-Headers",
				"Origin, X-Requested-With, Content-Type, Accept, Cookie, X-Token");
		response.setHeader("Access-Control-Allow-Methods",
				"GET, POST, PUT, DELETE, OPTIONS");
		response.addHeader("Access-Control-Max-Age", "1728000");
		response.addHeader("Access-Control-Allow-Credentials", "true");
		//logger.info("跨域");
	}


	/**
	 * base64解码请求头 Basic aW1vb2M6aW1vb2NzZWNyZXQ=
	 * Decodes the header into a username and password.
	 *
	 * @throws BadCredentialsException if the Basic header is not present or is not valid
	 * Base64
	 */

}
